const DB = require('../../../../utils/db')
const JwtUtil = require('../../../../utils/jwt')
/**
 * GET, 参数username
 * 搜索好友
 * 返回：搜索的用户的信息，与当前登录用户是否是好友关系，与当前登录用户申请信息
 */

module.exports =  async (ctx) => {
  // 获取token
  let token = ctx.request.header.authorization
  let jwt = new JwtUtil(token)
  // 用token获取到userid
  let userid = jwt.verifyToken()
  const friendInformation = await DB.query(
    `select * from user where username like '%${ctx.request.query.username}%'`
  )
  const getHasFriend = async (item) => {
    console.log('11111111')
    const hasFriend = await DB.query(
      `select * from user_friend where (userid='${userid}' and friendid='${item.userid}') or (userid='${item.userid}' and friendid='${userid}')`
    )
    if (hasFriend.length === 2) {
      // 已经是好友了
      item.isFriend = true
      console.log('是好友')
    } else {
      console.log('不是好友')
      // 不是好友,那么查询申请信息
      const applyres = await DB.query(
        `select applyStatus from user_apply where applicantid='${userid}' and respondentid='${item.userid}'`
      )
      console.log('333', applyres[0])
      item.isFriend = false
      item.applyStatus = applyres[0]?.applyStatus || -1
    }
  }
  for (let item of friendInformation) {
   await getHasFriend(item)
  }
    ctx.body = {
      code: 0,
      data: friendInformation,
    }
}
